package gaml.testing;

import static org.junit.Assert.assertEquals;
import gaml.error.GamlException;
import gaml.java.ClassSerializerStore;
import gaml.java.NodeObjectBridge;
import gaml.java.serializer.ComplexSerializerFactory;
import gaml.java.serializer.collection.HashMapSerializer;
import gaml.java.serializer.primitive.StringSerializer;
import gaml.yaml.MappingNode;
import gaml.yaml.ScalarNode;
import gaml.yaml.YamlNode;
import gaml.yaml.ahchor.YamlAnchorCodeStore;
import gaml.yaml.ahchor.YamlAnchorObjectStore;

import java.util.HashMap;

import org.junit.Test;


public class HashMapSerializerTest {

	@Test
	public void testDeserialize () throws GamlException {
		MappingNode node = new MappingNode (null);
		
		node.addChild (new ScalarNode (node).setValue ("key1").setTag ("java.lang.String"), new ScalarNode (node).setValue ("val1").setTag ("java.lang.String"));
		node.addChild (new ScalarNode (node).setValue ("key2").setTag ("java.lang.String"), new ScalarNode (node).setValue ("val2").setTag ("java.lang.String"));
		node.addChild (new ScalarNode (node).setValue ("key3").setTag ("java.lang.String"), new ScalarNode (node).setValue ("val3").setTag ("java.lang.String"));
		

		ClassSerializerStore store = new ClassSerializerStore ();
		store.setComplexFactory (new ComplexSerializerFactory (store));
		
		store.register (new StringSerializer ());
		store.register (new HashMapSerializer (store));
		
		HashMap <String, String> hashmap = (HashMap <String, String>) NodeObjectBridge.create (node, HashMap.class, store).parseNode (new YamlAnchorCodeStore ()).getObject ();
		
		assertEquals (3, hashmap.size ());
		assertEquals ("val2", hashmap.get ("key2"));
		
//		System.out.println (hashmap);
	}

	@Test
	public void testSerialize () throws GamlException {
		HashMap <String, String> map = new HashMap <String, String> ();
		
		map.put ("key1", "val1");
		map.put ("key2", "val2");
		map.put ("key3", "val3");
		map.put ("key4", "val4");
		;
		ClassSerializerStore store = new ClassSerializerStore ();
		store.setComplexFactory (new ComplexSerializerFactory (store));
		
		store.register (new StringSerializer ());
		store.register (new HashMapSerializer (store));
		
		YamlNode node = NodeObjectBridge.create (map, null, HashMap.class, store).parseObject (new YamlAnchorObjectStore ()).getNode ();
		
		assertEquals (4, node.getMappingChildren ().keySet ().size ());
		
		for (YamlNode key: node.getMappingChildren ().keySet ())
			for (YamlNode subkey: node.getChild (key).getMappingChildren ().keySet ())
					if ("key2".equals (subkey.getValue ())) assertEquals ("val2", node.getChild (key).getChild (subkey).getValue ());
	}

}
